//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useStores } from "@/hooks";
import type { AccessRecord } from "@/api/roadmap_user";
import { list_access, set_access, remove_access } from "@/api/roadmap_user";
import { listen } from '@tauri-apps/api/event';
import type * as NoticeType from '@/api/notice_type';
import { request } from "@/utils/request";
import { openRoadmapView } from "@/utils/roadmap";
import { Button, Card, Descriptions, List, message, Popover, Progress, Space } from "antd";
import { ExportOutlined, MoreOutlined } from "@ant-design/icons";
import moment from "moment";

const PAGE_SIZE = 24;


const AccessListPanel = () => {
    const userStore = useStores('userStore');

    const [accessList, setAccessList] = useState<AccessRecord[]>();
    const [totalAccessCount, setTotalAccessCount] = useState(0);
    const [curAccessPage, setCurAccessPage] = useState(0);

    const loadAccessList = async () => {
        const res = await request(list_access({
            session_id: userStore.sessionId,
            offset: curAccessPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setAccessList(res.record_list);
        setTotalAccessCount(res.total_count);
    };

    const openRoadmapWindow = async (roadmapId: string, roadmapName: string, canUpdate: boolean) => {
        await openRoadmapView(roadmapId, roadmapName, userStore.sessionId, false, canUpdate);
    };

    const removeAccess = async (roadmapId: string) => {
        await request(remove_access({
            session_id: userStore.sessionId,
            roadmap_id: roadmapId,
        }));
        await loadAccessList();
        message.info("删除访问记录成功");
    };

    const onAccessRoadmap = async (notice: NoticeType.client.AccessRoadmapNotice) => {
        if (userStore.sessionId == "") {
            return;
        }
        await request(set_access({
            session_id: userStore.sessionId,
            roadmap_id: notice.roadmapId,
            done_topic_count: notice.doneTopicCount,
            total_topic_count: notice.totalTopicCount,
            done_sub_topic_count: notice.doneSubTopicCount,
            total_sub_topic_count: notice.totalSubTopicCount,
        }));
        if (curAccessPage != 0) {
            setCurAccessPage(0);
        } else {
            loadAccessList();
        }
    }

    useEffect(() => {
        if (userStore.sessionId == "") {
            setAccessList([]);
            if (totalAccessCount != 0) {
                setTotalAccessCount(0);
            }
            if (curAccessPage != 0) {
                setCurAccessPage(0);
            }
        } else {
            loadAccessList();
        }
    }, [userStore.sessionId, curAccessPage]);


    useEffect(() => {
        if (userStore.sessionId == "") {
            return;
        }
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.ClientNotice?.AccessRoadmapNotice !== undefined) {
                onAccessRoadmap(notice.ClientNotice.AccessRoadmapNotice);
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, [userStore.sessionId]);

    return (
        <List rowKey="roadmap_id" dataSource={accessList} grid={{ gutter: 16 }}
            style={{ height: "calc(100vh - 130px)", overflowY: "scroll", padding: "10px 10px", overflowX: "hidden" }}
            pagination={{ current: curAccessPage + 1, total: totalAccessCount, pageSize: PAGE_SIZE, onChange: page => setCurAccessPage(page - 1), hideOnSinglePage: true }}
            renderItem={accessItem => (
                <List.Item>
                    <Card title={
                        <Button type="link" icon={<ExportOutlined />}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                openRoadmapWindow(accessItem.roadmap_id, accessItem.roadmap_title, accessItem.can_update_roadmap);
                            }}>
                            {accessItem.roadmap_title}
                        </Button>}
                        style={{ width: "300px" }} headStyle={{ backgroundColor: "#eee", padding: "0px 0px" }}
                        extra={
                            <Space style={{ marginRight: "10px" }}>
                                {moment(accessItem.time_stamp).format("YYYY-MM-DD HH:mm")}
                                <Popover trigger="click" placement="bottom" content={
                                    <Space direction="vertical">
                                        <Button type="link" danger onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            removeAccess(accessItem.roadmap_id);
                                        }}>删除</Button>
                                    </Space>
                                }>
                                    <MoreOutlined />
                                </Popover>
                            </Space>
                        }>
                        <Descriptions column={1} labelStyle={{ width: "70px", justifyContent: "right" }}>
                            <Descriptions.Item label="学习阶段">
                                <Progress percent={accessItem.total_topic_count == 0 ? 0 : accessItem.done_topic_count * 100 / accessItem.total_topic_count}
                                    format={() => `${accessItem.done_topic_count}/${accessItem.total_topic_count}`} size='small' />
                            </Descriptions.Item>
                            <Descriptions.Item label="知识点">
                                <Progress percent={accessItem.total_sub_topic_count == 0 ? 0 : accessItem.done_sub_topic_count * 100 / accessItem.total_sub_topic_count}
                                    format={() => `${accessItem.done_sub_topic_count}/${accessItem.total_sub_topic_count}`} size='small' />
                            </Descriptions.Item>
                        </Descriptions>
                        <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word", marginTop: "10px", height: "80px", overflowY: "scroll" }}>{accessItem.roadmap_desc}</pre>
                    </Card>
                </List.Item>
            )} />
    );
};

export default observer(AccessListPanel);